package crud;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;

import entities.Doctor;
import entities.ExamineDetail;
import entities.LabServiceDetail;
import entities.MedicineDetail;
import entities.PatientDetail;

public class ExamineDetailCRUD extends AbstractGRUD<ExamineDetail> {
	public ExamineDetailCRUD() {
		super(ExamineDetail.class);
	}

	public String create(Date appointmentDay, int idPatientDetail) {
		EntityManager em = this.getEm();
		String result = "success";
		try {
			em.getTransaction().begin();
			PatientDetail patient = new PatientDetailCRUD().readById(idPatientDetail);
			ExamineDetail examine = new ExamineDetail(appointmentDay, patient);
			em.persist(examine);
			em.getTransaction().commit();
		} catch (Exception e) {
			result = e.getMessage();
			em.getTransaction().rollback();
		}
		return result;
	}

	// Tao ExamineDetail va PatientDetail, danh cho DeskOfficer
	// public String create_Examine_Patient(String address, String emgContact,
	// String firstName, String lastName, Date appointmentDay) {
	// EntityManager em = this.getEm();
	// String result = "success";
	// try {
	// PatientDetail patient = new PatientDetail(address, emgContact, firstName,
	// lastName);
	// ExamineDetail examine = new ExamineDetail(appointmentDay, patient);
	// em.getTransaction().begin();
	// em.persist(patient);
	// em.persist(examine);
	// em.getTransaction().commit();
	//
	// } catch (Exception e) {
	// result = e.getMessage();
	// em.getTransaction().rollback();
	// }
	// return result;
	// }

	// Update examineDetail danh cho Doctor
	public String update(int idExamine, String disease, Date examineDay, Doctor doctor) {
		EntityManager em = this.getEm();
		String result = "success";
		try {
			em.getTransaction().begin();
			ExamineDetail examine = this.readById(idExamine);
			examine.setDisease(disease);
			examine.setDoctor(doctor);
			examine.setExamineDay(examineDay);
			em.merge(examine);
			em.getTransaction().commit();
		} catch (Exception e) {
			result = e.getMessage();
			em.getTransaction().rollback();
		}
		return result;
	}

	// Xoa toan bo ExamineDetail va labservice, medicine lien quan
	public String delete_Examine_Medicine_LabService(int idExamine) {
		EntityManager em = this.getEm();
		String result = "success";
		try {
			em.getTransaction().begin();
			ExamineDetail examine = this.readById(idExamine);

			List<LabServiceDetail> _labServiceDetail = examine.getLabServiceDetails();
			for (LabServiceDetail labServiceDetail : _labServiceDetail) {
				em.remove(labServiceDetail);
			}

			List<MedicineDetail> _MedicineDetails = examine.getMedicineDetails();
			for (MedicineDetail medicineDetail : _MedicineDetails) {
				em.remove(medicineDetail);
			}

			em.remove(examine);
			em.getTransaction().commit();
		} catch (Exception e) {
			result = e.getMessage();
			em.getTransaction().rollback();
		}
		return result;

	}
}
